package com.xgxx.chendawei.system.utils;

import com.xgxx.chendawei.system.utils.api.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;

/**
 * 提供给zuul下游使用
 */
@Slf4j
public class CommHttpUtil {

    public static final String USER_ID = "x-user-id";
    public static final String USER_NAME = "x-user-name";
    public static final String REMOTE_IP = "x-remote-ip";
    public static final String TOKEN = "access_token";
    public static final String REFRESH_TOKEN = "refresh_token";
    public static final String TOKEN_TIMEOUT = "timeout";
    //系统code(对主分店的系统)
    public static final String SYSTEM = "system_code";
    //分店ID
    public static final String SHOP_ID = "x-shop-id";
    //主店ID
    public static final String STORE_ID = "x-store-id";

    private static final String IP_UNKNOWN = "unknown";
    private static final String IP_LOCAL = "127.0.0.1";
    private static final int IP_LEN = 15;

    /**
     * 得到进入网关的客户ip
     *
     * @param request
     * @return
     */
    public static String getRemoteIp(HttpServletRequest request) {
        return request.getHeader(REMOTE_IP);
    }

    /**
     * 用户id
     *
     * @param request
     * @return
     */
    public static Long getUserId(HttpServletRequest request) {
        String userId = request.getHeader(USER_ID);
        if (StringUtils.isNotBlank(userId)) {
            try {
                return Long.parseLong(userId);
            } catch (Exception e) {
                log.warn("", e);
                throw new BusinessException("获取用户id异常", e);
            }
        }
        return null;
    }

    public static String getUserName(HttpServletRequest request) {
        return request.getHeader(USER_NAME);
    }

    public static boolean isAjax(HttpServletRequest request) {
        return request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");
    }

    public static Long getStoreId() {
        String spId = getRequestHeader(STORE_ID);
        return getLongParam(spId);
    }

    public static Long getShopId() {
        String spId = getRequestHeader(SHOP_ID);
        return getLongParam(spId);
    }

    public static String getRequestHeader(String header) {
        HttpServletRequest request = getHttpRequest();
        return request != null ? request.getHeader(header) : null;
    }

    private static Long getLongParam(String spId) {
        if (StringUtils.isBlank(spId) || spId.contains("null")) {
            return null;
        }
        try {
            return Long.parseLong(spId.trim());
        } catch (Exception e) {
            log.warn("", e);
        }
        return null;
    }

    public static Long getDataId() {
        Long shopId = getShopId();
        if (null != shopId) {
            return shopId;
        }
        return getStoreId();
    }

    public static HttpServletRequest getHttpRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes != null ? ((ServletRequestAttributes) requestAttributes).getRequest() : null;
    }


    public static String getIP(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ipAddress = headers.getFirst("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = Optional.ofNullable(request.getRemoteAddress())
                    .map(address -> address.getAddress().getHostAddress())
                    .orElse("");
            if (IP_LOCAL.equals(ipAddress)) {
                // 根据网卡取本机配置的IP
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("", e);
                }
            }
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > IP_LEN) {
            int index = ipAddress.indexOf(',');
            if (index > 0) {
                ipAddress = ipAddress.substring(0, index);
            }
        }
        return ipAddress;
    }
}
